import axios from 'axios'
let baseURL = 'http://localhost:3000'
axios.defaults.timeout = 100000 // 请求超时时间
export default function (type = 'get', url, data) {
  return new Promise((resolve, reject) => {
    type = type.toLowerCase()
    let config = {
      method: type,
      url: baseURL + url
    }
    if (type === 'get') {
      config.params = data
    } else if (type === 'post') {
      config.data = data
    }

    // 添加响应拦截器
    axios.interceptors.response.use(
      function (response) {
        // 响应数据处理
        console.log(response, 111)
        if (!response) return reject(response)
        let data = response.data
        switch (Number(data.code)) {
          case 401: // 登录超时
            console.log('登录超时')
            return response
          case 0: // 成功
            return response
          default:
            console.log(response.data.errmsg)
            reject(data.errmsg)
            break
        }
      },
      function (error) {
        // 响应错误处理
        // window.$message({ message: '错误信息', type: 'warning' })
        console.log('错误信息')
        return reject(error)
      }
    )
    axios(config)
      .then((res) => {
        if (res) {
          resolve(res.data)
        } else {
          reject(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
